package com.cn.qgx428.lazydiary.ui.activity.subActivity

import android.app.DatePickerDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.widget.DatePicker
import android.widget.LinearLayout
import android.widget.TextView
import com.cn.qgx428.lazydiary.Presenter.PlanPresenter
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.Utils.MConst
import com.cn.qgx428.lazydiary.adapter.RAdapter
import com.cn.qgx428.lazydiary.adapter.RViewHolder
import com.cn.qgx428.lazydiary.network.bean.PlanClockIn
import com.cn.qgx428.lazydiary.ui.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_plan_history.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*
import java.util.logging.SimpleFormatter

class PlanHistoryActivity : BaseActivity() {

    var planId = -1
    var adapter = ClockInAdapter(this, R.layout.adapter_plan_history_re)
    var historyClockIn: MutableList<PlanClockIn> = mutableListOf()
    var calendarStart : Long = 0
    var calenDarEnd : Long = 0

    override fun initUI() {
        hindActionBar()
        setStatuBarColor(R.color.myGreenBlack)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_plan_history)
        planId = intent.extras.getInt(MConst.PLAN_ID)
        initView()
        getHistoryData()
    }

    private fun getHistoryData() {
        PlanPresenter.getHistoryClockIn(planId,{
            historyClockIn = it as MutableList<PlanClockIn>
            adapter.setDatas(historyClockIn)
            if (historyClockIn.size > 0){
                calenDarEnd = getDate(historyClockIn.get(0).time)
                calendarStart = getDate(historyClockIn.get(historyClockIn.size - 1).time)
            } else{
                calenDarEnd = System.currentTimeMillis()
                calendarStart = System.currentTimeMillis()
            }
        })
    }

    //转换成时间戳
    private fun getDate(time: String): Long{
        val dateFormat = SimpleDateFormat("yyyy年MM月dd日")
        var date = Date()
        date = dateFormat.parse(time)
        return date.time
    }

    private fun initView() {
        planHistory_back.setOnClickListener({ finish() })
        planHistory_calendar.setOnClickListener({
            choseDayForClockIn()
        })
        planHistory_re.layoutManager = LinearLayoutManager(this)
        planHistory_re.adapter = adapter
    }

    private fun choseDayForClockIn() {
        // 显示第一次打卡和最后打卡之间的日期
        var date: Date = Date(calendarStart)
        val format = SimpleDateFormat("yyyy年MM月dd日")
        val time = format.format(date)
        val year = time.substring(0..time.indexOf("年")-1)
        val mouth = time.substring(time.indexOf("年")+1..time.indexOf("月")-1)
        val day = time.substring(time.indexOf("月")+1..time.indexOf("日")-1)
        var dialog = DatePickerDialog(this, object : DatePickerDialog.OnDateSetListener{
            override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
                onChoseClockInDay(year, month+1, dayOfMonth)
            }
        }, year.toInt(), mouth.toInt() ,day.toInt())
        dialog.datePicker.minDate = calendarStart
        dialog.datePicker.maxDate = calenDarEnd
        dialog.show()
      //  Log.d("what the hell " , "$year  $mouth   $day")
    }

    /**
     * 匹配合适打卡数据
     */
    private fun onChoseClockInDay(year: Int, mouth: Int, dayOfMonth: Int) {
        // 组织时间数据
        // 去除前置0
        var m = mouth.toString()
        if (m[0].equals('0'))
            m=m.substring(1..m.length-1)
        if (m.length == 1){ m = "0"+ m }
        var d = dayOfMonth.toString()
        if (d[0].equals('0'))
            d=d.substring(1..d.length-1)
        if (d.length == 1){ d = "0" + d }
        val time = "${year.toString()}年${m}月${d}日"
        Log.d("what the hell", "$time  form ")
        var match = false
        var position = 0
        for (i in 0..historyClockIn.size-1){
            if (historyClockIn.get(i).time.equals(time)){
                match = true
                position = i
                break
            }
        }
        // 匹配跳转HI页面
        if (match){
            startActivity<PlanHIctivity>(
                    MConst.PLAN_CLOCK_IN_DETAIL to historyClockIn.get(position))
        }else{
            toast("当日没有打卡哦～")
        }
    }

    /**
     * adapter
     */
    class ClockInAdapter: RAdapter<PlanClockIn>{
        constructor(context: Context, layoutId: Int): super(context, layoutId)

        override fun conver(holder: RViewHolder, data: PlanClockIn) {
            val remark = holder.getView<TextView>(R.id.adapter_planHistory_remark)
            val mouth = holder.getView<TextView>(R.id.adapter_planHistory_mouth)
            val day = holder.getView<TextView>(R.id.adapter_planhistory_day)
            val mainLayout = holder.getView<LinearLayout>(R.id.adapter_planHistory_mainLayout)

            mouth?.text = getMouth(data.time)
            day?.text = getDay(data.time)
            if (data.remark.equals(""))
                remark?.text = "今天很懒，什么都没有留下"
            else
                remark?.text = data.remark
            mainLayout?.setOnClickListener({
                mContext.startActivity<PlanHIctivity>(
                        MConst.PLAN_CLOCK_IN_DETAIL to data
                )
            })
        }

        fun getMouth(time: String): String{
            val start = time.indexOf("年") + 1
            val end = time.indexOf("月") - 1
            return time.substring(start..end)
        }

        fun getDay(time: String): String{
            val start = time.indexOf("月") + 1
            val end = time.indexOf("日") -1
            return time.substring(start..end)
        }
    }

}
